package com.lc.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.junit.Test;

import com.lc.util.StreamUtil;

public class TestRandomAccessFile {

	public static void main(String[] args) {
		try {
			RandomAccessFile aFile = new RandomAccessFile("nio-data.txt", "rw");
			FileChannel inChannel = aFile.getChannel();
			ByteBuffer buf = ByteBuffer.allocate(48);	//缓存
			int bytesRead = inChannel.read(buf);		//channel到缓存
			while (bytesRead != -1) {
				System.out.println("Read " + bytesRead);
				buf.flip();				//切换读模式
				while (buf.hasRemaining()) {
					System.out.println(buf.get());
				}
				buf.clear();
				bytesRead = inChannel.read(buf);
			}
			aFile.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {

		}
	}

	@Test
	public void fileTest() {
		File file = new File("nio-data.txt");
		System.out.println(file.getAbsolutePath());
		try {
			FileInputStream instream = new FileInputStream(file);
			String s = StreamUtil.inputStreamToString(instream, "UTF-8");
			System.out.println(s);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}